use anyhow::Result;
use sea_orm_migration::SchemaManager;
use infrastructure::entity::*;
pub use sea_orm::{ConnectionTrait, DatabaseConnection, DatabaseTransaction, Schema};
use sea_orm_migration::prelude::*;

use super::db_utils::{create_one_table as Cot, create_table_index as Cti, drop_one_table as Dot, init_data};


#[derive(DeriveMigrationName)]
pub struct Migration;

#[async_trait::async_trait]
impl MigrationTrait for Migration {
    async fn up(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        create_table(manager).await?;
        create_index(manager).await?;
        init_data(manager, "m20220101_000001_create_table").await?;
        Ok(())
    }

    async fn down(&self, manager: &SchemaManager) -> Result<(), DbErr> {
        drop_table(manager).await
    }
}

/// 创建表格
async fn create_table(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
    println!(">>>>>>>>>>>>>>>开始创建表格>>>>>>>>>>>>>>>");
    let db = manager.get_connection();
    let builder = manager.get_database_backend();
    let schema = Schema::new(builder);

    Cot(db, builder, &schema, sys_user::Entity).await?;

    Ok(())
}

//  创建索引
async fn create_index(m: &SchemaManager<'_>) -> Result<(), DbErr> {
    println!(">>>>>>>>>>>>>>>开始创建索引>>>>>>>>>>>>>>>");

    Cti(m, sys_user::Entity, "ind_username", vec![sys_user::Column::Username], "u").await?;
    Cti(m, sys_user::Entity, "ind_email", vec![sys_user::Column::Email], "i").await?;

    Ok(())
}

// 删除表格
async fn drop_table(manager: &SchemaManager<'_>) -> Result<(), DbErr> {
    println!(">>>>>>>>>>>>>>>开始删除表格>>>>>>>>>>>>>>>");

    Dot(manager, sys_user::Entity).await?;

    Ok(())
}